package com.springboot.component.dubbo;

import com.alibaba.dubbo.common.Constants;
import com.alibaba.dubbo.common.extension.Activate;
import com.alibaba.dubbo.rpc.*;
import com.alibaba.fastjson.JSON;
import com.springboot.exception.ServiceException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Service 层对外暴露的异常统一处理
 * 
 * @author dongda
 * @author zhuhanbing 
 */
@Activate(group = {Constants.PROVIDER, Constants.CONSUMER})
public class DubboExceptionFilter implements Filter {

    private final Logger log = LoggerFactory.getLogger(DubboExceptionFilter.class);

    @Override
    public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {

        Result result = invoker.invoke(invocation);

        if (result.hasException()) {
            String serviceName = invocation.getAttachment("interface");
            String methodName = invocation.getMethodName();

            String url = serviceName + "." + methodName;
            Object[] params = invocation.getArguments();

            com.springboot.dto.Result <Object> resultToReturn = null;
            
            Throwable ex = result.getException();
            if (ex instanceof ServiceException) {
                log.error("invoke url:{},___params:{}", url, JSON.toJSONString(params), ex);
                ServiceException se = (ServiceException) ex;
                resultToReturn = new com.springboot.dto.Result <Object>("error", ex.getMessage(), "", "", se.getCode());
            } else {
                log.error("invoke url:{},___params:{}", url, JSON.toJSONString(params), ex);
                resultToReturn = new com.springboot.dto.Result <Object>("error", "服务器异常", "", "", "500");
            }
            result = new RpcResult(resultToReturn);
        }
        return result;
    }

}
